package com.ruoyi.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.domain.entity.*;
import com.ruoyi.project.domain.query.PhaseDictionaryQuery;
import com.ruoyi.project.mapper.PhaseDictionaryMapper;
import com.ruoyi.project.service.*;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class PhaseDictionaryServiceImpl extends ServiceImpl<PhaseDictionaryMapper, PhaseDictionary> implements IPhaseDictionaryService {
    @Resource
    private PhaseDictionaryMapper phaseDictionaryMapper;

    @Resource
    IPhaseDictionaryService phaseConfigService;

    @Resource
    IProjectParticipanService projectJoinService;

    @Resource
    IProjectPhaseService phaseService;

    @Resource
    IProjectService projectService;

    @Resource
    ISysPostService postService;

    @Resource
    IProjectAttachmentService fileService;

    @Resource
    ISysDictDataService dictDataService;

    @Resource
    IProjectPayService payService;

    @Resource
    IProjectImplementService implementService;

    @Resource
    IProjectAccountingService accountingService;

    @Resource
    IProjectWarrantyService warrantyService;

    @Resource
    IProjectCostingService costingService;

    //分页
    @Override
    public TableDataInfo getDictionaryPage(PhaseDictionaryQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<PhaseDictionary> list = phaseDictionaryMapper.getList(query);
        return new TableDataInfo(list, page.getTotal());
    }

    //新增
    @Override
    public Boolean saveDictionary(PhaseDictionary phaseDictionary) {
        System.out.println("======" + phaseDictionary);
        int insert = phaseDictionaryMapper.insert(phaseDictionary);
        return insert > 0;
    }

    @Override
    public Boolean updateDictionary(PhaseDictionary phaseDictionary) {
        return this.updateById(phaseDictionary);
    }

    @Override
    public Boolean deleteDictionarys(Integer id) {
        return this.removeById(id);
    }

    @Override
    public PhaseDictionary selectPhaseDictionaryById(Integer id) {
        return this.getById(id);
    }

    @Override
    public Map<String, Object> getNextPermission(PhaseDictionaryQuery query) {

        Map<String, Object> map = new HashMap<>();
        boolean permission = false;//默认无权限
        String message = "";
        map.put("permission", permission);
        map.put("message", message);

//        if (SecurityUtils.hasRole("admin") | SecurityUtils.hasRole("gjadmin")) {
//            permission = true;
//            message = "高级管理员有全部权限";
//            map.put("permission", permission);
//            map.put("message", message);
//            return map;
//        }

        if (query == null || query.getId() == null || query.getProjectNo() == null) {
            throw new RuntimeException("请求接口失败");
        }

        //1.获取这个阶段的配置
        PhaseDictionary config = phaseConfigService.getById(query.getId());
        if (config == null) {
            throw new RuntimeException("获取环节配置失败");
        }

        //设置其他权限
        getAllPermissions(query, map);

        //2.获取当前登录用户信息id
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
        List<Integer> operatorIdList = config.getOperatorId();

        //查询对应项目对应环节未完成的
        LambdaQueryWrapper<ProjectPhase> phaseWrapper = new QueryWrapper<ProjectPhase>().lambda()
                .eq(ProjectPhase::getProjectNo, query.getProjectNo())
                .eq(ProjectPhase::getPhaseId, query.getId())
                .eq(ProjectPhase::getStatus, "1");//写死 查询未完成的 1是进行中 2是已完成
        ProjectPhase phaseOne = phaseService.getOne(phaseWrapper);
        if (phaseOne == null) {//已完成
            permission = false;
            map.put("permission", permission);
            message = "该环节已完成";
            map.put("message", message);
            return map;
        }
        List<Integer> auditList = phaseOne.getAudit();//需要判断指定的人有没有审核过
        //如果指定了操作人  直接比对登录人的id和指定的人id是否相同 相同且没有点过下一步并且状态是1 进行中 则返回ture
        //有无点过下一步逻辑 点过后会往project_phase对应阶段的audit中插入已点过下一步的人的id （没有指定操作人的插入的人岗位id）
        if (operatorIdList != null && operatorIdList.size() > 0) {
            boolean isUserIdInList = operatorIdList.contains(userId.intValue());
            //如果登录的人id在指定的操作人中
            if (isUserIdInList) {
                if (auditList != null && auditList.size() > 0) {//有没有审核过
                    boolean isAudit = auditList.contains(userId.intValue());
                    if (isAudit) {//如果审核过 返回false隐藏按钮
                        permission = false;
                        map.put("permission", permission);
                        message = "当前用户已审核完成：" + userId + ":" + nickName;
                        map.put("message", message);
                        return map;
                    } else {
                        permission = false;
                        map.put("permission", permission);
                        message = "等待当前用户审核：" + userId + ":" + nickName;
                        map.put("message", message);
                        return map;
                    }
                } else {
                    permission = true;
                    map.put("permission", permission);
                    message = "等待当前用户审核：" + userId + ":" + nickName;
                    map.put("message", message);
                    return map;
                }
            } else {//如果当前登录人的id没有在指定的操作人中 返回false  隐藏按钮
                permission = false;
                map.put("permission", permission);
                message = "当前用户不属于指定的操作人：" + userId + ":" + nickName;
                map.put("message", message);
                return map;
            }
        }

        //3.如果没有指定操作人 需要获取当前阶段操作人岗位去匹配
        //配置中的全部岗位
        List<Integer> allPostIdList = config.getPostId();
        //是否需要当前阶段的全部操作人同意
        //获取这个项目所有的参与人员和参与人员对应的岗位
        LambdaQueryWrapper<ProjectParticipan> JoinPersonWrapper = new QueryWrapper<ProjectParticipan>().lambda()
                .eq(query.getProjectNo() != null, ProjectParticipan::getProjectNo, query.getProjectNo());
        List<ProjectParticipan> joinPersonList = projectJoinService.list(JoinPersonWrapper);

        //循环配置中的岗位
        boolean foundMatch = false;

        for (Integer configPostId : allPostIdList) {
            for (ProjectParticipan joinPerson : joinPersonList) {
                //添加的参与人id
                Long participantId = joinPerson.getParticipantId();
                //添加的岗位id
                Long postId = joinPerson.getPostId();
                //是否审核过
                boolean isAudit = false;
                if (auditList != null) {
                    isAudit = auditList.contains(postId.intValue());
                }

                //条件  如果没有审核过 且用户id和岗位id和记录中的匹配
                if (!isAudit && userId.intValue() == participantId.intValue() && postId.intValue() == configPostId.intValue()) {
                    permission = true;
                    map.put("permission", permission);
                    message = "当前审核人" + userId + ":" + nickName;
                    map.put("message", message);
                    foundMatch = true;
                    break; // 退出内层循环
                }
            }
            if (foundMatch) {
                break; // 退出外层循环
            }
        }
        return map;
    }

    public Map<String, Object> getAllPermissions(PhaseDictionaryQuery query, Map<String, Object> map) {
        if (query == null || query.getId() == null || query.getProjectNo() == null) {
            throw new RuntimeException("请求接口失败");
        }
        Long userId = SecurityUtils.getUserId();
        //1.获取这个阶段的配置
        PhaseDictionary config = phaseConfigService.getById(query.getId());
        if (config == null) {
            throw new RuntimeException("获取环节配置失败");
        }
        LambdaQueryWrapper<ProjectParticipan> JoinPersonWrapper = new QueryWrapper<ProjectParticipan>().lambda()
                .eq(query.getProjectNo() != null, ProjectParticipan::getProjectNo, query.getProjectNo());
        List<ProjectParticipan> joinPersonList = projectJoinService.list(JoinPersonWrapper);
        //2.获取这个人在参与人员中的岗位
        // 2. 获取用户对应的岗位 ID 列表
        List<Integer> postIds = new ArrayList<>();
        for (ProjectParticipan joinPerson : joinPersonList) {
            Long participantId = joinPerson.getParticipantId();
            if (String.valueOf(userId).equals(String.valueOf(participantId))) { // 匹配用户 ID
                // 添加对应的岗位 ID
                Long postId = joinPerson.getPostId();
                postIds.add(postId.intValue());
            }
        }

// 3. 该环节可添加参与人员的岗位 ID
        List<Integer> addPerson = config.getAddPerson();
        boolean hasAddPersonPermission = postIds.stream().anyMatch(addPerson::contains);
        map.put("addPerson", hasAddPersonPermission);

        if (SecurityUtils.hasRole("admin") || SecurityUtils.hasRole("gjadmin") || SecurityUtils.getUserId().equals(100L)) {
            map.put("addPerson", true);

        }

// 4. 可添加付款信息的岗位
        List<Integer> addPay = config.getAddPay();
        boolean hasAddPayPermission = postIds.stream().anyMatch(addPay::contains);
        map.put("addPay", hasAddPayPermission);

// 5. 可添加附件信息的岗位
        List<Integer> addFile = config.getAddFile();
        boolean hasAddFilePermission = postIds.stream().anyMatch(addFile::contains);
        map.put("addFile", hasAddFilePermission);

// 6. 可添加实施日志的岗位
        List<Integer> addImplement = config.getAddImplement();
        boolean hasAddImplementPermission = postIds.stream().anyMatch(addImplement::contains);
        map.put("addImplement", hasAddImplementPermission);

// 7. 可添加质保信息的岗位
        List<Integer> addWarranty = config.getAddWarranty();
        boolean hasAddWarrantyPermission = postIds.stream().anyMatch(addWarranty::contains);
        map.put("addWarranty", hasAddWarrantyPermission);

// 8. 添加核算信息的岗位
        List<Integer> addAccounting = config.getAddAccounting();
        boolean hasAddAccountingPermission = postIds.stream().anyMatch(addAccounting::contains);
        map.put("addAccounting", hasAddAccountingPermission);


        //9.是否是财务
        List<String> cwList = new ArrayList<>();
        cwList.add("6");

        boolean cw = cwList.stream().anyMatch(addAccounting::contains);
        map.put("cw", cw);

        //10.是否是管理员
        boolean admin = SecurityUtils.hasRole("admin") || SecurityUtils.hasRole("gjadmin");
        map.put("admin", admin);


        return map;
    }

    @Override
    public Map<String, Object> getAllPermission(PhaseDictionaryQuery query) {
        Map<String, Object> map = new HashMap<>();
        String message = "";
        if (query == null || query.getId() == null || query.getProjectNo() == null) {
            throw new RuntimeException("请求接口失败");
        }
        Long userId = SecurityUtils.getUserId();
        //1.获取这个阶段的配置
        PhaseDictionary config = phaseConfigService.getById(query.getId());
        if (config == null) {
            throw new RuntimeException("获取环节配置失败");
        }
        LambdaQueryWrapper<ProjectParticipan> JoinPersonWrapper = new QueryWrapper<ProjectParticipan>().lambda()
                .eq(query.getProjectNo() != null, ProjectParticipan::getProjectNo, query.getProjectNo());
        List<ProjectParticipan> joinPersonList = projectJoinService.list(JoinPersonWrapper);
        //2.获取这个人在参与人员中的岗位
        // 2. 获取用户对应的岗位 ID 列表
        List<String> postIds = new ArrayList<>();
        for (ProjectParticipan joinPerson : joinPersonList) {
            Long participantId = joinPerson.getParticipantId();
            if (String.valueOf(userId).equals(String.valueOf(participantId))) { // 匹配用户 ID
                // 添加对应的岗位 ID
                Long postId = joinPerson.getPostId();
                postIds.add(String.valueOf(postId));
            }
        }

// 3. 该环节可添加参与人员的岗位 ID
        List<Integer> addPerson = config.getAddPerson();
        boolean hasAddPersonPermission = postIds.stream().anyMatch(addPerson::contains);
        map.put("addPerson", hasAddPersonPermission);

// 4. 可添加付款信息的岗位
        List<Integer> addPay = config.getAddPay();
        boolean hasAddPayPermission = postIds.stream().anyMatch(addPay::contains);
        map.put("addPay", hasAddPayPermission);

// 5. 可添加附件信息的岗位
        List<Integer> addFile = config.getAddFile();
        boolean hasAddFilePermission = postIds.stream().anyMatch(addFile::contains);
        map.put("addFile", hasAddFilePermission);

// 6. 可添加实施日志的岗位
        List<Integer> addImplement = config.getAddImplement();
        boolean hasAddImplementPermission = postIds.stream().anyMatch(addImplement::contains);
        map.put("addImplement", hasAddImplementPermission);

// 7. 可添加质保信息的岗位
        List<Integer> addWarranty = config.getAddWarranty();
        boolean hasAddWarrantyPermission = postIds.stream().anyMatch(addWarranty::contains);
        map.put("addWarranty", hasAddWarrantyPermission);

// 8. 添加核算信息的岗位
        List<Integer> addAccounting = config.getAddAccounting();
        boolean hasAddAccountingPermission = postIds.stream().anyMatch(addAccounting::contains);
        map.put("addAccounting", hasAddAccountingPermission);

        return map;
    }

    @Override
    public Map<String, Object> checkRule(PhaseDictionaryQuery query) {
        Map<String, Object> map = new HashMap<>();
        boolean permission = true;//默认无权限
        String message = "";
        PhaseDictionary config = this.getById(query.getId());
        String projectNo = query.getProjectNo();

        map.put("permission", permission);
        map.put("message", message);

        if (config == null) {
            permission = false;
            message = "获取环节配置信息失败";
            map.put("permission", permission);
            map.put("message", message);
            return map;
        }
        if (StringUtils.isEmpty(projectNo)) {
            permission = false;
            message = "获取项目编号失败";
            map.put("permission", permission);
            map.put("message", message);
            return map;
        }


        //1.校验参与人员
        Map<String, Object> joinPersonMap = checkJoinPerson(config, projectNo);
        if (!((Boolean) joinPersonMap.get("permission"))) {
            return joinPersonMap;
        }

        //2.校验附件类型
        Map<String, Object> fileTypeMap = checkFileType(config, projectNo);
        if (!((Boolean) fileTypeMap.get("permission"))) {
            return fileTypeMap;
        }

        //3.校验付款信息
        Map<String, Object> payMap = checkPay(config, projectNo);
        if (!((Boolean) payMap.get("permission"))) {
            return payMap;
        }


        //4.校验实施日志信息
        Map<String, Object> implementMap = checkImplement(config, projectNo);
        if (!((Boolean) implementMap.get("permission"))) {
            return implementMap;
        }

        //4.校验核算信息
        Map<String, Object> accountingtMap = checkAccounting(config, projectNo);
        if (!((Boolean) accountingtMap.get("permission"))) {
            return accountingtMap;
        }

        //4.校验质保信息
        Map<String, Object> warrantyMap = checkWarranty(config, projectNo);
        if (!((Boolean) warrantyMap.get("permission"))) {
            return warrantyMap;
        }


        return map;
    }

    //判断该环节是否添加了必须的参与人
    public Map<String, Object> checkJoinPerson(PhaseDictionary config, String projectNo) {
        Map<String, Object> map = new HashMap<>();
        boolean permission = true;
        String message = "";
        map.put("permission", permission);
        map.put("message", message);
        //1.检查需要的参与人员有没有齐全 先获取这个项目的所有参与人员
        LambdaQueryWrapper<ProjectParticipan> JoinPersonWrapper = new QueryWrapper<ProjectParticipan>().lambda()
                .eq(ProjectParticipan::getProjectNo, projectNo);
//                .eq(ProjectParticipan::getPhaseId,config.getId());//如果前面环节已经添加了？
        List<ProjectParticipan> joinPersonList = projectJoinService.list(JoinPersonWrapper);

        // 提取所有的postId
        List<Long> postIdList = joinPersonList.stream()
                .map(ProjectParticipan::getPostId) // 提取 postId
                .collect(Collectors.toList());    // 收集为 List

        //2.再获取配置信息中的参与人员
        List<Integer> needPersonPostId = config.getNeedPersonId();
        boolean joinPersonCheck = true;
        //判断currPerAndPostId是否存在与
        for (Integer currPerAndPostId : needPersonPostId) {
            //循环必须添加的参与人岗位 每一个都需要在已添加的参与人员中匹配 如果匹配不到提示需要添加该人员
            boolean joinPersonChecks = postIdList.contains(Long.valueOf(currPerAndPostId));
            //只要有其中一个没找到就提示
            if (joinPersonChecks == false) {
                permission = joinPersonChecks;
                SysPost sysPost = postService.selectPostById(Long.valueOf(currPerAndPostId));
                message = "该环节必须添加" + sysPost.getPostName();
                map.put("permission", permission);
                map.put("message", message);
                break;
            }
        }
        return map;
    }

    //判断该环节是否添加了必须的附件
    public Map<String, Object> checkFileType(PhaseDictionary config, String projectNo) {
        Map<String, Object> map = new HashMap<>();
        boolean permission = true;
        String message = "";
        map.put("permission", permission);
        map.put("message", message);

        Project projectInfo = projectService.getById(projectNo);
        BigDecimal contractAmount = projectInfo.getContractAmount();
        BigDecimal settlementAmount = projectInfo.getSettlementAmount() != null ? projectInfo.getSettlementAmount() : BigDecimal.ZERO;
        //1.检查需要添加的附件 判断是否是全量

        LambdaQueryWrapper<ProjectAttachment> fileWrapper = new QueryWrapper<ProjectAttachment>().lambda()
                .eq(ProjectAttachment::getProjectNo, projectNo);
//                .eq(ProjectAttachment::getPhaseId,config.getId());//如果在其他环节已经添加了？
        List<ProjectAttachment> fileList = fileService.list(fileWrapper);

        // 提取所有的文件类型
        List<String> fileTypeList = fileList.stream()
                .map(ProjectAttachment::getAttachmentType)
                .collect(Collectors.toList());

        //是否全量添加 0否1是
        Integer allFile = config.getAllFile();
        //获取配置中的需要的文件类型
        List<String> needFileType = config.getNeedFileType();
        if (allFile == 1) {//必须全部上传
            //循环必须添加的附件类型 每一个都需要在已上传的附件中存在 否则提示
            for (String fileType : needFileType) {
                // 检查 needFileType 是否为空
                if (needFileType == null || needFileType.isEmpty()) {
                    map.put("permission", false);
                    map.put("message", "未配置需要上传的文件类型");
                    return map;
                }
                boolean fileChecks = fileTypeList.contains(fileType);
                if (fileChecks == false) {
                    permission = fileChecks;
                    String fileTypeName = dictDataService.selectDictLabel("file_type", fileType);
                    message = "该环节必须上传:" + fileTypeName;
                    map.put("permission", permission);
                    map.put("message", message);

                    //特殊判断 合同金额和结算金额相等 不用再上传竣工结算清单
                    if (fileTypeName.contains("竣工结算清单")) {
                        if (contractAmount.compareTo(settlementAmount) == 0) {
                            map.put("permission", true);
                        }
                    }

                    if (!(boolean) map.get("permission")) {
                        break;
                    }

                }
            }
        } else {//只上传其中之一就可以
            String resultName = "";
            for (String fileType : needFileType) {
                boolean fileChecks = fileTypeList.contains(fileType);
                String fileTypeName = dictDataService.selectDictLabel("file_type", fileType);
                if (fileChecks) {
                    permission = fileChecks;
                    message = "已满足上传的附件:" + fileTypeName;
                    map.put("permission", permission);
                    map.put("message", message);
                    break;
                } else {
                    resultName = resultName + fileTypeName + " ";
                    permission = false; // 如果没有任何匹配，最终设置权限为 false
                    map.put("permission", permission);
                }

            }
            if (permission == false) {
                message = "需要上传以下附件的其中之一：" + resultName;
            }
            map.put("message", message);
        }


        //判断  有结算金额取结算金额 没有取合同金额  判断竣工结算清单或正式清单的金额是否对得上


        return map;
    }

    public void checkCosting(String projectNo) {
        if (StringUtils.isEmpty(projectNo)) {
            throw new RuntimeException("服务器出错,请联系管理员!");
        }

        Project project = projectService.getById(projectNo);
        // 合同金额
        BigDecimal contractAmount = project.getContractAmount();
        if (contractAmount == null) {
            throw new RuntimeException("后台服务出错,请联系管理员!");
        }
        // 结算金额
        BigDecimal settlementAmount = project.getSettlementAmount();

        // 有结算金额取结算金额，没有取合同金额，并记录来源名称
        BigDecimal resultAmount;
        String amountSource; // 用于记录金额来源
        if (settlementAmount != null) {
            resultAmount = settlementAmount;
            amountSource = "结算金额";
        } else {
            resultAmount = contractAmount;
            amountSource = "合同金额";
        }

        LambdaQueryWrapper<ProjectCosting> costingWrapper = new QueryWrapper<ProjectCosting>().lambda();
        costingWrapper.eq(ProjectCosting::getProjectNo, projectNo);
        List<ProjectCosting> list = costingService.list(costingWrapper);
        BigDecimal total = BigDecimal.ZERO;
        for (ProjectCosting projectCosting : list) {
            total = total.add(projectCosting.getDiscountPrice() != null ?
                    projectCosting.getDiscountPrice() :
                    projectCosting.getTotalPrice());
        }

        // 计算两个数的差的绝对值
        BigDecimal diff = resultAmount.subtract(total).abs();
        // 判断差值是否 <= 1
        boolean isDifferenceLessThanOne = diff.compareTo(BigDecimal.ONE) <= 0;

        if (isDifferenceLessThanOne) {
            System.out.println("两个数值相差在 1 以内（含等于 1）");
        } else {
            System.out.println("两个数值相差大于 1");
            // 抛出异常时包含金额来源信息
            throw new RuntimeException(amountSource +
                    "为" + resultAmount.toString() + "与清单金额" +total + "不一致,请检查！");
        }
    }

    //判断该环节是否需要付款信息
    public Map<String, Object> checkPay(PhaseDictionary config, String projectNo) {
        // 参数校验
        if (config == null || projectNo == null) {
            throw new IllegalArgumentException("参数 config 或 projectNo 不能为空");
        }

        Map<String, Object> map = new HashMap<>();
        boolean permission = true;
        String message = "";
        map.put("permission", permission);
        map.put("message", message);

        try {
            // 检查是否需要付款
            if (config.getNeedPay() == 1) {
                LambdaQueryWrapper<ProjectPay> payWrapper = new QueryWrapper<ProjectPay>().lambda()
                        .eq(ProjectPay::getProjectNo, projectNo)
                        .eq(ProjectPay::getPhaseId, config.getId());
                List<ProjectPay> payList = payService.list(payWrapper);

                // 判断付款记录是否存在
                if (payList == null || payList.isEmpty()) {
                    permission = false;
                    message = "该环节必须添加付款信息";
                    map.put("permission", permission);
                    map.put("message", message);
                }
            }
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            permission = false;
            message = "检查付款信息时发生错误：" + e.getMessage();
            map.put("permission", permission);
            map.put("message", message);
        }

        return map;
    }

    //判断该环节是否需要实施日志信息
    public Map<String, Object> checkImplement(PhaseDictionary config, String projectNo) {
        Map<String, Object> map = new HashMap<>();
        boolean permission = true;
        String message = "";

        // 非空校验
        if (config == null) {
            map.put("permission", false);
            map.put("message", "配置信息为空");
            return map;
        }
        if (StringUtils.isBlank(projectNo)) {
            map.put("permission", false);
            map.put("message", "项目编号不能为空");
            return map;
        }

        try {
            if (config.getNeedImplement() == 1) {
                LambdaQueryWrapper<ProjectImplement> implementWrapper = new QueryWrapper<ProjectImplement>().lambda()
                        .eq(ProjectImplement::getProjectNo, projectNo)
                        .eq(ProjectImplement::getPhaseId, config.getId());
                List<ProjectImplement> payList = implementService.list(implementWrapper);

                if (payList == null || payList.isEmpty()) {
                    permission = false;
                    message = "该环节必须添加实施日志";
                }
            }
        } catch (Exception e) {
            // 异常处理
            permission = false;
            message = "后端接口异常：" + e.getMessage();
        }

        map.put("permission", permission);
        map.put("message", message);
        return map;
    }

    //判断该环节是否需要核算信息
    public Map<String, Object> checkAccounting(PhaseDictionary config, String projectNo) {
        // 初始化返回结果
        Map<String, Object> result = new HashMap<>();
        boolean permission = true;
        String message = "";

        try {
            // 参数校验
            if (config == null) {
                permission = false;
                message = "配置信息为空";
            } else if (StringUtils.isBlank(projectNo)) {
                permission = false;
                message = "项目编号不能为空";
            } else if (config.getNeedAccounting() == 1) {
                // 查询条件构建
                LambdaQueryWrapper<ProjectAccounting> accountingWrapper = new QueryWrapper<ProjectAccounting>().lambda()
                        .eq(ProjectAccounting::getProjectNo, projectNo)
                        .eq(ProjectAccounting::getPhaseId, config.getId());

                // 查询核算信息
                List<ProjectAccounting> accountingList = accountingService.list(accountingWrapper);

                if (accountingList == null || accountingList.isEmpty()) {
                    permission = false;
                    message = "您还没有添加核算信息";
                }
            }
        } catch (Exception e) {
            // 异常处理
            permission = false;
            message = "检查核算信息时发生错误：" + e.getMessage();
        }

        // 设置返回值
        result.put("permission", permission);
        result.put("message", message);
        return result;
    }

    //判断该环节是否需要质保信息
    public Map<String, Object> checkWarranty(PhaseDictionary config, String projectNo) {
        // 初始化返回结果
        Map<String, Object> result = new HashMap<>();
        boolean permission = true;
        String message = "";

        // 判断是否需要质保信息
        if (config.getNeedWarranty() == 1) {
            // 查询质保信息
            LambdaQueryWrapper<ProjectWarranty> warrantyWrapper = new QueryWrapper<ProjectWarranty>().lambda()
                    .eq(ProjectWarranty::getProjectNo, projectNo)
                    .eq(ProjectWarranty::getPhaseId, config.getId());
            List<ProjectWarranty> warrantyList = warrantyService.list(warrantyWrapper);

            // 如果质保信息为空，则设置权限为 false 并返回提示信息
            if (warrantyList.isEmpty()) {
                permission = false;
                message = "该环节必须添加质保信息";
            }
        }

        // 将结果写入返回 map
        result.put("permission", permission);
        result.put("message", message);
        return result;
    }
}
